<template>
  <div>
    <el-steps class="steps" :active="step" align-center>
      <el-step title="商品基本信息"></el-step>
      <el-step title="添加库存信息"></el-step>
      <el-step title="添加移动端详情"></el-step>
    </el-steps>

    <el-form class="one" ref="form" :model="form" label-width="80px">
      <div v-if="step == 1" class="item1">
        <p>基本信息</p>
        <el-row :gutter="24">
          <el-col :span="6" :offset="0">
            <el-form-item label="商品名称">
              <el-input v-model="form.product.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="商品编码">
              <el-input v-model="form.product.productSn"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="商品分类">
              <el-select
                style="width: 160px"
                v-model="form.product.sortobj"
                placeholder="请选择"
                @change="changesort"
                value-key="id"
              >
                <el-option
                  v-for="item in sortlist"
                  :key="item.category.id"
                  :label="item.category.name"
                  :value="item.category"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="商品品牌">
              <el-select
                style="width: 160px"
                v-model="form.product.brandobj"
                placeholder="请选择"
                @change="changebrand"
                value-key="id"
              >
                <el-option
                  v-for="item in brandlist"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col style="margin-right: -40px" :span="2" :offset="0"
            >商品描述</el-col
          >
          <el-col :span="11" :offset="0">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="form.product.description"
            >
            </el-input>
          </el-col>
        </el-row>
        <p>商品属性</p>
        <el-row :gutter="24">
          <el-col :span="6" :offset="0">
            <el-form-item label="商品原价">
              <el-input-number
                v-model="form.product.originalPrice"
                :min="1"
                :max="100000"
                label="商品原价"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="促销类型">
              <el-select
                v-model="form.product.promotionType"
                disabled
                placeholder="请选择"
              >
                <el-option
                  v-for="item in brandlist"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="活动价格">
              <el-input-number
                v-model="form.product.promotionPrice"
                :min="1"
                :max="10"
                :disabled="true"
                label="商品原价"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="商品重量">
              <el-input-number
                v-model="form.product.weight"
                :min="1"
                :max="10"
                label="商品重量"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6" :offset="0">
            <el-form-item label="审核状态">
              <el-switch
                v-model="form.product.verifyStatus"
                active-color="#13ce66"
                inactive-color="#DCDFE6"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="是否上架">
              <el-switch
                v-model="form.product.publishStatus"
                active-color="#13ce66"
                inactive-color="#DCDFE6"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12" :offset="0">
            <el-form-item label="缩略图">
              <el-upload
                action="http://localhost:9528/lejuAdmin/material/uploadFileOss"
                list-type="picture-card"
                :headers="headers"
                :on-success="uploadSuccess"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <p>其他信息</p>
        <el-row :gutter="24">
          <el-col :span="6" :offset="0">
            <el-form-item label="推荐状态">
              <el-switch
                v-model="form.product.recommendStatus"
                active-color="#13ce66"
                inactive-color="#DCDFE6"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="新品状态">
              <el-switch
                v-model="form.product.newStatus"
                active-color="#13ce66"
                inactive-color="#DCDFE6"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="预告商品">
              <el-switch
                v-model="form.product.previewStatus"
                active-color="#13ce66"
                inactive-color="#DCDFE6"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6" :offset="0">
            <el-form-item label="关键词">
              <el-input v-model="form.product.keywords"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="库存预警">
              <el-input-number
                v-model="form.product.lowStock"
                :min="1"
                :max="10"
                :disabled="true"
                label="库存预警"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="商品排序">
              <el-input-number
                v-model="form.product.sort"
                :min="1"
                :max="10"
                label="商品排序"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12" :offset="0">
            <el-form-item label="产品服务">
              <el-checkbox-group v-model="serviceIds">
                <el-checkbox label="1">无忧退货</el-checkbox>
                <el-checkbox label="2">快速退款</el-checkbox>
                <el-checkbox label="3">免费包邮</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <div style="margin: 0 auto; text-align: center" class="btn">
          <el-button @click="step = 2" type="primary"
            >下一步,填写库存信息</el-button
          >
        </div>
      </div>

      <div v-if="step == 2" class="item1 item2">
        <p>商品SKU消息</p>
        <el-row :gutter="24">
          <el-col :span="8" :offset="0">
            <el-form-item label="标题">
              <el-input v-model="form.product.title"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="副标题">
              <el-input v-model="form.product.subTitle"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="8" :offset="0">
            <el-form-item label="画册图片">
              <el-upload
                action="http://localhost:9528/lejuAdmin/material/uploadFileOss"
                list-type="picture-card"
                :headers="headers"
                :on-success="uploadSuccess1"
              >
                <i class="el-icon-plus"></i>
                <div class="el-upload__tip" slot="tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <p>
          SKU设置
          <el-button
            style="margin-left: 20px"
            size="small"
            type="primary"
            @click="createList"
            >生成SKU列表</el-button
          >

          <el-input
            style="width: 150px; margin-left: 40px"
            v-model="skuCname"
            placeholder="请输入SKU中文名字"
            size="small"
          ></el-input>
          <el-input
            style="width: 150px; margin-left: 5px"
            v-model="skuEname"
            placeholder="请输入SKU英文名字"
            size="small"
          ></el-input>
          <el-button
            @click="addSkuSort"
            style="margin-left: 5px"
            size="small"
            type="primary"
            >新增SKU</el-button
          >
        </p>
        <el-row
          v-for="(item, index1) in skuSort"
          :key="'item' + index1"
          :gutter="24"
        >
          <el-col :span="24" :offset="0">
            <el-form-item :label="item.name">
              <el-checkbox-group v-model="item.checkList">
                <el-tag
                  v-for="(con, index) in item.sortList"
                  :key="'con' + index"
                  closable
                  @close="delitem(index, index1, con)"
                  style="margin-right: 20px"
                >
                  <el-checkbox :label="con"></el-checkbox>
                </el-tag>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-for="(item, index) in skuSort" :key="index" :gutter="24">
          <el-col :span="16" :offset="0">
            <el-form-item :label="item.name">
              <el-input
                style="width: 300px; margin-right: 20px"
                v-model="item.nowinput"
              ></el-input>
              <el-button @click="addItem(item.eName)" type="primary"
                >新增{{ item.name }}</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="skuList.length" :gutter="24">
          <el-col :span="24" :offset="0">
            <el-table :data="skuList" border style="width: 100%">
              <el-table-column
                align="center"
                label="序号"
                type="index"
                width="50"
              >
              </el-table-column>
              <el-table-column align="center" prop="date" label="图片">
                <template slot-scope="scope">
                  <el-upload
                    class="avatar-uploader"
                    action="http://localhost:9528/lejuAdmin/material/uploadFileOss"
                    :show-file-list="false"
                    :headers="headers"
                    :on-success="handleAvatarSuccess"
                    @click.native="whichone(scope.row.uuid)"
                  >
                    <img
                      style="width: 100px; height: 100px"
                      :src="scope.row.pic"
                      class="avatar"
                    />
                  </el-upload>
                </template>
              </el-table-column>

              <el-table-column
                v-for="(item, index) in skuSort"
                :key="'item' + index"
                align="center"
                :label="item.name"
                :prop="item.eName"
              >
                <template slot-scope="scope"
                  ><el-input v-model="scope.row[item.eName]"></el-input
                ></template>
              </el-table-column>

              <el-table-column align="center" label="库存" prop="stock">
                <template slot-scope="scope"
                  ><el-input
                    v-model="scope.row.stock"
                    placeholder="请输入库存"
                  ></el-input
                ></template>
              </el-table-column>

              <el-table-column align="center" label="预警库存" prop="lowStock">
                <template slot-scope="scope"
                  ><el-input
                    placeholder="请输入预警库存"
                    v-model="scope.row.lowStock"
                  ></el-input
                ></template>
              </el-table-column>
              <el-table-column align="center" label="锁定库存" prop="lockStock">
                <template slot-scope="scope"
                  ><el-input
                    placeholder="请输入锁定库存"
                    v-model="scope.row.lockStock"
                  ></el-input
                ></template>
              </el-table-column>
              <el-table-column align="center" label="SKU编码" prop="skuCode">
                <template slot-scope="scope"
                  ><el-input
                    placeholder="请输入SKU编码"
                    v-model="scope.row.skuCode"
                  ></el-input
                ></template>
              </el-table-column>
              <el-table-column align="center" label="销量" prop="sale">
                <template slot-scope="scope"
                  ><el-input
                    placeholder="请输入销量"
                    v-model="scope.row.sale"
                  ></el-input
                ></template>
              </el-table-column>

              <el-table-column align="center" label="操作" prop="sale">
                <template slot-scope="scope">
                  <el-button
                    @click="delSkuItem(scope.row.uuid)"
                    type="danger"
                    size="small"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <div class="btn">
          <el-button @click="step = 1">返回上一步</el-button>
          <el-button @click="step3" type="primary"
            >下一步,填写移动端详情</el-button
          >
        </div>
      </div>

      <div v-if="step == 3" class="item3 item">
        <el-row :gutter="24">
          <el-col :span="24" :offset="0">
            <el-form-item label="商品描述">
              <tinEditor ref="tin"></tinEditor>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24" :offset="0">
            <el-form-item label="备注">
              <el-input
                v-model="form.product.note"
                placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="btn">
          <el-button @click="step = 2">返回上一步</el-button>
          <el-button v-if="isAdd" @click="submitAdd" type="primary"
            >提交保存</el-button
          >
          <el-button v-else @click="submitUpdata" type="primary"
            >提交更新</el-button
          >
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import { v1 as myV1 } from "uuid";
import brandApi from "@/api/goods/brand/index";
import goodsApi from "@/api/goods/goodsList/index";
import tinEditor from "@/components/Tinymce/index.vue";
import { getToken } from "@/utils/myAuth";
export default {
  components: { tinEditor },

  data() {
    return {
      step: 1,
      serviceIds: [],
      isAdd: true,
      brandlist: [],
      sortlist: [],
      skuList: [],
      skuCname: "",
      skuEname: "",
      imageUrl: "",
      checkList: [
        {
          name: "颜色",
          itemList: [],
        },
        {
          name: "尺寸",
          itemList: [],
        },
      ],
      skuSort: [
        {
          name: "颜色",
          eName: "color",
          nowinput: "",
          sortList: [],
          checkList: [],
          useList: [],
        },
        {
          name: "尺寸",
          eName: "size",
          nowinput: "",
          sortList: [],
          checkList: [],
          useList: [],
        },
      ],
      form: {
        pmsSkuStockList: [
          {
            createTime: "",
            id: "",
            lockStock: 0,
            lowStock: 0,
            modifyTime: "",
            pic: "",
            price: 0,
            productId: "",
            promotionPrice: 0,
            sale: 0,
            skuCode: "",
            spData: "",
            stock: 0,
          },
        ],
        product: {
          brandobj: {},
          sortobj: {},
          albumPics: "",
          brandId: "",
          brandName: "",
          createTime: "",
          deleteStatus: 0,
          description: "",
          detailDesc: "",
          detailHtml: "",
          detailMobileHtml: "",
          detailTitle: "",
          feightTemplateId: "",
          giftGrowth: 0,
          giftPoint: 0,
          id: "",
          keywords: "",
          lowStock: 0,
          modifyTime: "",
          name: "",
          newStatus: 0,
          note: "",
          originalPrice: 0,
          pic: "",
          previewStatus: 0,
          price: 0,
          productAttributeCategoryId: "",
          productCategoryId: "",
          productCategoryName: "",
          productSn: "",
          promotionEndTime: "",
          promotionPerLimit: 0,
          promotionPrice: 0,
          promotionStartTime: "",
          promotionType: 0,
          publishStatus: 0,
          recommendStatus: 0,
          sale: 0,
          serviceIds: "",
          sort: 0,
          stock: 0,
          subTitle: "",
          unit: "",
          usePointLimit: 0,
          verifyStatus: 0,
          weight: 0,
        },
      },
    };
  },

  created() {
    console.log(this.$route.query.goodsid);
    // 编辑商品为表单赋值
    if (this.$route.query.goodsid) {
      this.isAdd = false;
      goodsApi.productSkusDetail(this.$route.query.goodsid).then((res) => {
        console.log(res);
        this.form.product = res.data.product;
        this.form.pmsSkuStockList = res.data.skus;
        this.skuList = res.data.skus;
        this.serviceIds = res.data.product.serviceIds.split(",");
      });
    }
    // 获取品牌列表
    brandApi.findAllBrand().then((res) => {
      console.log(res);
      this.brandlist = res.data.items;
    });
    // 获取分类的列表
    goodsApi.getAllCategory().then((res) => {
      console.log(res);
      this.sortlist = res.data.items;
    });
  },

  mounted() {},

  methods: {
    // 填写移动端详细
    step3() {
      this.step = 3;
      // this.$refs.tin.setContent(this.form.product.detailDesc);
    },
    // 更新提交
    submitUpdata() {
      this.form.pmsSkuStockList = this.skuList;
      this.form.product.detailDesc = this.$refs.tin.getContent();
      var obj = JSON.parse(JSON.stringify(this.form));
      obj.product.serviceIds = this.serviceIds.join(",");
      goodsApi.updateProductAndSkus(obj).then((res) => {
        console.log(res);
        if (res.success) {
          this.$message({
            message: "更新商品成功",
            type: "success",
          });
          this.$router.go(-1);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 新增提交
    submitAdd() {
      this.form.pmsSkuStockList = this.skuList;
      this.form.product.detailDesc = this.$refs.tin.getContent();
      var obj = JSON.parse(JSON.stringify(this.form));
      obj.product.serviceIds = this.serviceIds.join(",");
      goodsApi.addProductAndSkus(obj).then((res) => {
        console.log(res);
        if (res.success) {
          this.$message({
            message: "添加商品成功",
            type: "success",
          });
          this.$router.go(-1);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 删除sku表格内的某一项
    delSkuItem(id) {
      var index = this.skuList.findIndex((el) => {
        return el.uuid == id;
      });
      this.skuList.splice(index, 1);
      console.log(index);
    },
    // sku每一项添加图片
    whichone(id) {
      console.log(id);
      this.choiceid = id;
    },
    handleAvatarSuccess(res) {
      console.log(res);
      var index = this.skuList.findIndex((el) => {
        return el.uuid == this.choiceid;
      });
      this.skuList[index].pic = res.data.fileUrl;
      console.log(index);
    },
    // 生成sku列表
    createList() {
      let list = [];
      this.skuSort.forEach((el) => {
        var usename = el.eName;
        el.checkList.forEach((e) => {
          var obj = {};
          obj = {};
          obj[usename] = e;
          el.useList.push(obj);
        });
        list.push(el.useList);
      });
      console.log(list);

      var arrlist = list.reduce((total, current) => {
        var arr = [];
        var arr1 = [];
        console.log(total, current);
        for (var i = 0; i < total.length; i++) {
          for (var j = 0; j < current.length; j++) {
            arr1 = [];
            if (total[i] instanceof Array) {
              arr1.push(total[i], current[j]);
              console.log();
            } else {
              arr1.push(total[i], current[j]);
            }
            arr.push(arr1);
          }
        }
        return arr;
      });

      console.log(arrlist);
      var finnally = [];
      arrlist.forEach((el) => {
        var obj = {
          skuCode: "", // 编码
          name: "",
          price: "", // 价格
          pic: "", // 图片
          stock: "", // 库存
          lowStock: "", // 预警库存
          lockStock: "", //锁定库存
          sale: "", //销量
          uuid: myV1(),
          spData: [],
        };
        el.flat(this.skuSort.length - 1).forEach((e) => {
          for (var key in e) {
            obj[key] = e[key];
          }
        });
        finnally.push(obj);
      });

      console.log(finnally);

      finnally.forEach((el) => {
        this.skuSort.forEach((e) => {
          el.spData.push({
            key: e.name,
            value: el[e.eName],
          });
        });
        el.spData = JSON.stringify(el.spData);
      });

      this.skuList = finnally;
    },
    // 删除某一项sku名字的复选框
    delitem(index, index1, item) {
      console.log(index, index1, item);
      this.skuSort[index1].sortList.splice(index, 1);
      var delindex = this.skuSort[index1].checkList.findIndex((el) => {
        return el == item;
      });
      console.log(delindex);
      if (delindex == -1) {
      } else {
        this.skuSort[index1].checkList.splice(delindex, 1);
      }
    },
    // 每一项的sku新增属性
    addItem(name) {
      console.log(name);
      this.skuSort.forEach((el) => {
        if (el.eName == name) {
          console.log("object");
          el.sortList.push(el.nowinput);
        }
        el.nowinput = "";
      });
    },
    // 新增sku名字
    addSkuSort() {
      console.log(this.skuCname);
      if (this.skuCname == "" || this.skuEname == "") {
        this.$message({
          message: "两者缺一不可",
          type: "warning",
        });
      } else {
        var obj = {
          name: this.skuCname,
          eName: this.skuEname,
          nowinput: "",
          sortList: [],
          checkList: [],
          useList: [],
        };
        this.skuSort.push(obj);
        this.skuCname = this.skuEname = "";
      }
    },
    // 选分类
    changesort(e) {
      console.log(e);
      this.form.product.productCategoryId = e.id;
      this.form.product.productCategoryName = e.name;
      console.log(this.form.product.brandobj);
    },
    // 选品牌
    changebrand(e) {
      console.log(e);
      this.form.product.brandId = e.id;
      this.form.product.brandName = e.name;
    },
    // 上传缩略图
    uploadSuccess(res, file) {
      console.log(res);
      this;
      this.form.product.pic = res.data.fileUrl;
    },
    // 上传画册
    uploadSuccess1(res, file) {
      console.log(res);
      this;
      this.form.product.albumPics = res.data.fileUrl;
    },
  },

  computed: {
    headers() {
      const token = getToken();
      return { token };
    },
  },

  watch: {},
};
</script>

<style scoped lang='scss'>
.steps {
  background-color: #fff;
  padding: 30px 0;
}
.one {
  width: 97%;
  margin: 15px auto;
  padding: 0 40px;
  background-color: #fff;
  margin-top: 20px;
  overflow: hidden;
  p {
    width: 100%;
    padding: 20px 0;
    padding-top: 0;
    margin: 20px auto;
    margin-top: 40px;
    border-bottom: 1px solid #eee;
  }
  .btn {
    padding: 40px 0;
    text-align: center;
  }
}
.item3 {
  padding: 40px 0;
}
</style>

